<template>
  <a-spin :spinning='confirmLoading'>
    <j-form-container :disabled='formDisabled'>
      <!-- 主表单区域 -->
      <a-form-model ref='form' :model='model' :rules='validatorRules' slot='detail'>
        <a-row>
          <a-col :span='12'>
            <a-form-model-item label='单据编号' :labelCol='labelCol' :wrapperCol='wrapperCol' prop='code'>
              <a-input v-model='model.code' placeholder='请输入版样编号'></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span='12'>
            <a-form-model-item label='物料编号' :labelCol='labelCol' :wrapperCol='wrapperCol' prop='goodsCode'>
              <a-input v-model='model.goodsCode' disabled placeholder='请输入物料编号'></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span='12'>
            <a-form-model-item label='物料名称' :labelCol='labelCol' :wrapperCol='wrapperCol' prop='goodsName'>
              <a-input v-model='model.goodsName' disabled placeholder='请输入物料名称'></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span='12'>
            <a-form-model-item label='物料规格' :labelCol='labelCol' :wrapperCol='wrapperCol' prop='goodsSpec'>
              <a-input v-model='model.goodsSpec' disabled placeholder='请输入物料规格'></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span='12'>
            <a-form-model-item label='物料单位' :labelCol='labelCol' :wrapperCol='wrapperCol' prop='goodsUnit'>
              <j-dict-select-tag type='list' v-model='model.goodsUnit' disabled dictCode='ji_unit' placeholder='请输入物料单位' />
            </a-form-model-item>
          </a-col>
          <!--          <a-col :span="24" >-->
          <!--            <a-form-model-item label="标识" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="mark">-->
          <!--              <a-input v-model="model.mark" placeholder="请输入标识" ></a-input>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!--          <a-col :span="24" >-->
          <!--            <a-form-model-item label="年份(2位)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">-->
          <!--              <a-input v-model="model.year" placeholder="请输入年份(2位)" ></a-input>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!--          <a-col :span="24" >-->
          <!--            <a-form-model-item label="排产单号(4位)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderNumber">-->
          <!--              <a-input v-model="model.orderNumber" placeholder="请输入排产单号(4位)" ></a-input>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!--          <a-col :span="24" >-->
          <!--            <a-form-model-item label="包装形式(1位)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packaType">-->
          <!--              <a-input v-model="model.packaType" placeholder="请输入包装形式(1位)" ></a-input>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!--          <a-col :span="24" >-->
          <!--            <a-form-model-item label="包装规格(2位)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packSpec">-->
          <!--              <a-input v-model="model.packSpec" placeholder="请输入包装规格(2位)" ></a-input>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!--          <a-col :span="24" >-->
          <!--            <a-form-model-item label="版本号(2位)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="version">-->
          <!--              <a-input v-model="model.version" placeholder="请输入版本号(2位)" ></a-input>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!--          <a-col :span="24" >-->
          <!--            <a-form-model-item label="改版内容" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="revisedContent">-->
          <!--              <a-input v-model="model.revisedContent" placeholder="请输入改版内容" ></a-input>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <!--          <a-col :span="24" >-->
          <!--            <a-form-model-item label="改版时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="revisedTime">-->
          <!--              <j-date placeholder="请选择改版时间" v-model="model.revisedTime" style="width: 100%" />-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
        </a-row>
      </a-form-model>
      <!-- 显示图片的 Card 区域
      <a-card title="版样在线预览" v-if ="erpGoodsPatternDetailTable.dataSource.length > 0" >
        <div v-if="erpGoodsPatternDetailTable.dataSource.length === 0">暂无文件</div>
        <div v-else>
          <div v-for="(file, index) in erpGoodsPatternDetailTable.dataSource" :key="index">
              <div class="pdf-container">
                <iframe :src="handlePreviewFilePDF(file.name)" frameborder="0" width="100%" height="500px"></iframe>
              </div>
          </div>
        </div>
      </a-card> -->



    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model='activeKey' @change='handleChangeTabs'>
      <a-tab-pane tab='版样列表' :key='refKeys[0]' :forceRender='true'>
        <j-vxe-table
          keep-source
          :ref='refKeys[0]'
          :loading='erpGoodsPatternDetailTable.loading'
          :columns='erpGoodsPatternDetailTable.columns'
          :dataSource='erpGoodsPatternDetailTable.dataSource'
          :maxHeight='300'
          :disabled='formDisabled'
          :rowNumber='true'
          :rowSelection='true'
          :toolbar='false'
        >
        <template v-slot:action="{row}">
                    <a @click="handlePreviewFile(row)">预览</a>
                  </template>
      </j-vxe-table>
   
      </a-tab-pane>
      
    </a-tabs>
  </a-spin>
</template>

<script>

import { getAction,putAction } from '@/api/manage'
import { FilePreview } from '@/utils/tslCommon'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import { Base64 } from 'js-base64'
import store from '@/store'

export default {
  name: 'ErpGoodsPatternForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      model: { code: '', goodsName: '', goodsCode: '', goodsSpec: '', goodsUnit: '', materielId: '' },
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        code: [
          { required: true, message: '请输入版样编号!' }
        ]
      },
      refKeys: ['erpGoodsPatternDetail'],
      tableKeys: ['erpGoodsPatternDetail'],
      activeKey: 'erpGoodsPatternDetail',
      // 版样更改管理明细
      erpGoodsPatternDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '版样附件',
            key: 'name',
            type: JVXETypes.file,
            token: true,
            responseName: 'message',
            width: '200px',
            placeholder: '请选择文件',
            defaultValue: ''
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
          // {
          //   title: '操作',
          //   key: 'operation',
          //   // 使用customRender来自定义列渲染
          //   customRender: (text, record) => {
          //     return (
          //       <a-button type="primary" onClick={() => handleClick(record.key)}>
          //         预览
          //       </a-button>
          //     );
          //   },
          // },
        ]
      },
      url: {
        add: '/pattern/erpGoodsPattern/add',
        edit: '/pattern/erpGoodsPattern/edit',
        queryById: '/pattern/erpGoodsPattern/queryById',
        erpGoodsPatternDetail: {
          list: '/pattern/erpGoodsPattern/queryErpGoodsPatternDetailByMainId'
        }
      }
    }
  },
  props: [{
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  }, 'patternGoods'],
  computed: {
    formDisabled() {
      return this.disabled
    }
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    
    //this.getSequenceNum()
  },
  methods: {

    handlePreviewFile(row) {
      let filePath =row.name
      FilePreview(filePath);
    },
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },

    getSequenceNum() {
      let url = '/sys/fillRule/executeRuleByCode/pattern_request_code'
      putAction(url, {}).then((res) => {
        console.log("获取单据编号"+res);
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.code = res.result
          this.$forceUpdate();
        }
      })
    },
    // handlePreviewFilePDF(rowpath) {
    //  let realPath= this.getImgView(rowpath)
    //   let base = window._CONFIG.onlinePreviewDomainURL + '/onlinePreview?url='
    //   let codename = Base64.encode(realPath)
    //   let url = base + codename
    //   console.log('预览pdf地址是：'+url)
    //   return url
    // },
    // getPfCode() {
    //   postAction('/sys/fillRule/executeRuleByCode/bybh', {}).then(res => {
    //     this.model.code = res.result
    //   })
    // },
    /** 遍历所有的JVxeTable实例 */
    eachAllTable(callback) {
      // 开始遍历
      this.getAllTable().then(tables => {
        console.log('tables', tables)
        tables.forEach((item, index) => {
          if (typeof callback === 'function') {
            callback(item, index)
          }
        })
      })
    },
    add() {
      // this.edit(this.modelDefault);
      // this.getPfCode();
      console.log(this.patternGoods)
      // getAction('/base/erpGoods/queryById',{id:this.patternGoods[0]}).then(res=>{
      //   if(res.success){
      //     let records = res.result
      this.model.goodsName = this.patternGoods.name
      this.model.goodsCode = this.patternGoods.code
      this.model.goodsSpec = this.patternGoods.noneSpec
      this.model.goodsUnit = this.patternGoods.meUnit
      this.model.materielId = this.patternGoods.id
      //   }
      // })
      this.eachAllTable((item) => {
        //update-begin-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
        setTimeout(() => {
          item.addRows()
        }, 30)
        //update-end-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349

        this.getSequenceNum()
      })
    },
    addBefore() {
      this.erpGoodsPatternDetailTable.dataSource = []
      this.getSequenceNum()
    },
    edit(record) {
      getAction('/base/erpGoods/queryById', { id: record.materielId }).then(res => {
        if (res.success) {
          let records = res.result
          Vue.set(record, 'goodsName', records.name)
          Vue.set(record, 'goodsCode', records.code)
          Vue.set(record, 'goodsSpec', records.noneSpec)
          Vue.set(record, 'goodsUnit', records.meUnit)
          this.model = Object.assign({}, record)
          this.visible = true
          this.editAfter()
        }
      })

    },
    getAllTable() {
      let values = this.tableKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.erpGoodsPatternDetail.list, params, this.erpGoodsPatternDetailTable)

      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([]).then(() => {
          resolve(allValues)
        }).catch(e => {
          if (e.error === VALIDATE_FAILED) {
            // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
            this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
          } else {
            console.error(e)
          }
        })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        erpGoodsPatternDetailList: allValues.tablesValue[0].tableData
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    }

  }
}
</script>

<style scoped>
</style>